<?php

  $time = microtime();
  $time = explode(' ', $time);
  $time = $time[1] + $time[0];
  $start = $time;

include("../config.php");

	include('../lang/'.$default_language.'.php');
	include("../inc/common.php");
if ( OS_is_logged() AND OS_is_admin() ) {
	include("../inc/class.database.php");
	include("../inc/db_connect.php");
	
if ( file_exists('../'.OS_CURRENT_THEME_PATH.'/functions.php') )
    include('../'.OS_CURRENT_THEME_PATH.'/functions.php');

$return = "";

function OS_UpdateScoresTable( $name = "" ) {
    global $db;
	
	$name = safeEscape( trim($name) );
	if ( !empty($name) ) {
	$presult = $db->query("SELECT * FROM scores WHERE LOWER(name) = LOWER('".$name."')");
    if( $limit = $db->num_rows($presult) <= 0 ) {
    $UpdateNameScoreTable = $db->query("INSERT INTO scores(category, name)VALUES('dota_elo','".$name."')");
    }
	
    //Get updated result
    $resultScore = $db->query("SELECT player,score FROM ".OSDB_STATS." WHERE LOWER(player) = LOWER('".$name."')");
    $rScore = $db->fetch_array($resultScore,'assoc');
    //update "scores" table
    $UpdateScoreTable = $db->query("UPDATE `scores` SET `score` = '".$rScore["score"]."' 
	WHERE LOWER(name) = LOWER('".$rScore["player"]."') ");
	
	}
}


	if (isset($_GET["reset"])) {
	$r1 = $db->query("UPDATE ".OSDB_GAMES." SET stats = 0 WHERE stats = 1");
	//$r2 = $db->query("DELETE FROM ".OSDB_STATS."");
	//$r3 = $db->query("ALTER table ".OSDB_STATS." auto_increment = 1");
	$r4 = $db->query("TRUNCATE table ".OSDB_STATS." ");
	}
	
	if ( isset($_GET["start"]) ) {
	//GET ALL ADMINS (in array)
	$result = $db->query("SELECT * FROM ".OSDB_ADMINS." WHERE id>=1");
	$admins = array();
	while ($row = $db->fetch_array($result,'assoc')) { $admins[]= strtolower($row["name"]);  }
	//GET ALL USERS FROM SAFELIST
	$result = $db->query("SELECT * FROM ".OSDB_SAFELIST." WHERE id>=1");
	$safelist = array();
	while ($row = $db->fetch_array($result,'assoc')) { $safelist[]= strtolower($row["name"]);	}
	
	$_result = $db->query( "SELECT id FROM ".OSDB_GAMES." 
	WHERE LOWER(map) LIKE LOWER('%dota%') AND stats = 0 AND duration>='".$MinDuration."' LIMIT ".$updateGames." " );
	
	 while ($row = $db->fetch_array($_result,'assoc')) {
	 $gid = $row["id"];
	 $result = $db->query("SELECT winner, dp.gameid, gp.colour, newcolour, kills, deaths, assists, creepkills, creepdenies, neutralkills, towerkills, gold,  raxkills, courierkills, g.duration as duration,
	   gp.name as name, 
	   gp.ip as ip, gp.spoofed, gp.loadingtime, gp.spoofedrealm, gp.reserved, gp.left,
	   b.name as banname, b.expiredate, b.warn
	   FROM ".OSDB_DP." AS dp 
	   LEFT JOIN ".OSDB_GP." AS gp ON gp.gameid = dp.gameid and dp.colour = gp.colour 
	   LEFT JOIN ".OSDB_DG." AS dg ON dg.gameid = dp.gameid 
	   LEFT JOIN ".OSDB_GAMES." AS g ON g.id = dp.gameid 
	   LEFT JOIN ".OSDB_BANS." as b ON b.name=gp.name
	   WHERE dp.gameid='".$gid."'
	   GROUP by gp.name
	   ORDER BY newcolour");
	   
	   if ($db->num_rows($result) <=0)  $update = $db->query("UPDATE ".OSDB_GAMES." SET stats = 1 WHERE id = $gid ;");
	   
	   while ($list = $db->fetch_array($result,'assoc')) {
		$kills=$list["kills"];
		$deaths=$list["deaths"];
		$assists=$list["assists"];
		$creepkills=$list["creepkills"];
		$creepdenies=$list["creepdenies"];
		$neutralkills=$list["neutralkills"];
		$towerkills=$list["towerkills"];
		$raxkills=$list["raxkills"];
		$courierkills=$list["courierkills"];
		$duration=$list["duration"];
		$name=mysql_real_escape_string(trim($list["name"]));
		$IPaddress = $list["ip"];
		$banname=$list["banname"];
		$win=$list["winner"];
		$newcolour=$list["newcolour"];
		$warn_expire = $list["expiredate"];
		$warn = $list["warn"];
		
		$spoofed = $list["spoofed"];
		$realm = $list["spoofedrealm"];
		$loadingtime = $list["loadingtime"];
		$reserved = $list["reserved"];
				
		if ( empty($warn_expire ) ) $warn_expire  = '0000-00-00 00:00:00'; 
		
		if ( $warn>=1 ) $warn_qry = 'warn = '.$warn.', '; else $warn_qry = "";
				
		if ( in_array( strtolower($name), $admins ) )   $is_admin = 1; else $is_admin = 0;
		if ( in_array( strtolower($name), $safelist ) ) $is_safe = 1;  else $is_safe  = 0;
		
		if ( strtolower($banname)==strtolower($name) ) $BANNED = 1; else $BANNED = 0;
		
		if ($win==1 AND $newcolour<=5) {$winner = 1; $loser = 0;}
		if ($win==0) {$winner = 0; $loser = 0;}
		if ($win==2 AND $newcolour>5) {$winner = 1; $loser = 0;}
		if ($win==1 AND $newcolour>5) {$winner = 0; $loser = 1;}
		if ($win==2 AND $newcolour<=5) {$winner = 0; $loser = 1;}
		
		if ($winner == 1) $score = $ScoreStart + $ScoreWins;
		if ($winner == 0) $score = $ScoreStart - $ScoreLosses;
		if ($win==0) $score = $ScoreStart;
		
		if ( $list["left"] <= ($list["duration"] - $MinDuration) ) {
		   $leaver = 1; $score = "";
		} else $leaver = 0;
		
		// Score formula for each game (uncomment below to user score formula)
		// $scoreFormula = (((($kills-$deaths+$assists*0.5+$towerkills*0.5+$raxkills*0.2+($courierkills+$creepdenies)*0.1+$neutralkills*0.03+$creepkills*0.03) * .2)+($score)));
		
		// $score = $scoreFormula;
		// MEW FIELDS: $realm $loadingtime $reserved
		
		if ($win==0) $draw = 1; else $draw = 0;
		if (!empty($name) AND $duration >= $MinDuration) {
		$result2 = $db->query("SELECT player FROM ".OSDB_STATS." WHERE LOWER(player) = LOWER('$name')");
		//Create a new player...
		  if ( $db->num_rows($result2) <=0) {
          $sql3 = "INSERT INTO ".OSDB_STATS."(player, score, games, wins, losses, draw, kills, deaths, assists, creeps, denies, neutrals, towers, rax, banned, ip, warn_expire, warn, admin, safelist, loading, realm, reserved, leaver) 
		  VALUES('$name','$score',1,$winner,$loser,$draw,$kills,$deaths,$assists,$creepkills,$creepdenies,$neutralkills, $towerkills, $raxkills, $BANNED, '$IPaddress', '$warn_expire', '$warn', '$is_admin', '$is_safe', '$loadingtime', '$realm', '$reserved', '$leaver')";

          } else {
		  //...or update player data
		  if ($winner == 1) $score = "score = score + $ScoreWins,";
		  if ($winner == 0) $score = "score = score - $ScoreLosses,";
		  if ($win==0) $score = "";
		  $sql3 = "UPDATE ".OSDB_STATS." SET 
		  $score
		  player = '$name',
		  games = games+1, 
		  wins = wins +$winner,
		  losses = losses+$loser,
		  draw = draw + $draw,
		  kills = kills + $kills,
		  deaths = deaths + $deaths,
		  assists = assists + $assists,
		  creeps = creeps + $creepkills,
		  denies = denies + $creepdenies,
		  neutrals = neutrals + $neutralkills,
		  towers = towers + $towerkills,
		  rax = rax + $raxkills,
          banned = $BANNED,
		  ip = '$IPaddress',
		  warn_expire = '$warn_expire',
		  $warn_qry
		  admin = '$is_admin',
		  safelist = '$is_safe',
		  realm = '$realm',
		  loading = loading + $loadingtime,
		  reserved = reserved + $reserved,
		  leaver = leaver + $leaver
		  WHERE LOWER(player) = LOWER('$name');";
		   }
		  $result3 = $db->query($sql3);
		
		//OS_UpdateScoresTable( $name  );
		
		
		 }
		 //$return.="\nGame ($gid) updated!";
	     //Update "games" table so we can know what games have been updated
	     $update = $db->query("UPDATE ".OSDB_GAMES." SET stats = 1 WHERE id = $gid ;");
		 
	   }
	   $return.="\nGame ($gid) updated!";
	 }
	 
	 
	}
	
if (isset($_GET["reset"])) {
   header("location: ".OS_HOME."adm/update_stats.php"); die;
}

	$result = $db->query( "SELECT COUNT(*) FROM ".OSDB_GAMES." 
	WHERE LOWER(map) LIKE LOWER('%dota%') AND stats = 0 AND duration>='".$MinDuration."'" );
    $r = $db->fetch_row($result);
    $TotalGamesForUpdate = $r[0];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php if (isset($_GET["refresh"]) AND is_numeric($_GET["refresh"]) AND $TotalGamesForUpdate>=1) {  ?>
    <meta http-equiv="refresh" content="<?=(int) $_GET["refresh"]?>" />
<?php } ?>
<?php if (isset($_GET["reset"])) {  ?>
    <meta http-equiv="refresh" content="2" />
<?php } ?>
 	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<meta http-equiv="content-style-type" content="text/css" />
	<meta name="author" content="Ivan Antonijevic" />
	<meta name="rating" content="Safe For Kids" />
 	<meta name="description" content="<?=$HomeDesc?>" />
	<meta name="keywords" content="<?=$HomeKeywords?>" />
	<title><?=$HomeTitle?></title>
	<link rel="stylesheet" href="<?=OS_HOME?>themes/blogger/style.css" type="text/css" />
	
</head>
  
<body>

<div id="wrapper" style="height:960px">
<div id="logo">
  <h1><?=$HomeTitle?></h1>
</div>  

  <div class="main-nav-main" style="position:fixed; top: 0px; left: 0px;">
   <div class="ct-wrapper">
<ul class="dd_menu">
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/">Dashboard</a>
    <ul>
	  <li><a href="<?=OS_HOME?>adm/?cfg">Configuration</a> </li>
	</ul>
  </li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?games">Games</a></li>
  <li><a class="menuButtons" href="<?=$website?>adm/?players">Players</a></li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?posts">Posts</a></li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?comments">Comments</a></li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?users">Users</a></li>
  <li>
  <a class="menuButtons" href="<?=OS_HOME?>adm/?bans">Bans</a>
    <ul>
	  <li><a href="<?=OS_HOME?>adm/?ban_reports">Ban Reports</a></li>
	  <li><a href="<?=OS_HOME?>adm/?ban_appeals">Ban Appeals</a></li>
	</ul>
  </li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?admins"><?=$lang["admins"]?></a></li>
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?plugins">Plugins</a></li>
  <li><a class="menuButtons" href="javascript:;">Misc</a>
     <ul>
	   <li><a href="<?=OS_HOME?>adm/?guides">Guides</a></li>
	 <?php if (isset($GameListPatch) AND $GameListPatch==1) { ?>
	   <li><a href="<?=OS_HOME?>adm/?gamelist">Gamelist</a></li>
	 <?php } ?>
	   <li><a href="<?=OS_HOME?>adm/?heroes"><?=$lang["heroes"]?></a></li>
	   <li><a href="<?=OS_HOME?>adm/?items"><?=$lang["items"]?></a></li>
	   <li><a href="<?=OS_HOME?>adm/?about_us"><?=$lang["about_us"]?></a></li>
	   <li><a href="<?=OS_HOME?>adm/?safelist"><?=$lang["safelist"]?></a></li>
	   <li><a href="<?=OS_HOME?>adm/?notes">Notes</a></li>
	   <li><a href="<?=OS_HOME?>adm/?optimize_tables">Optimize Tables</a></li>
	 </ul>
  </li>
  
  <li><a class="menuButtons" href="<?=OS_HOME?>adm/?logout"><?=$_SESSION["username"]?></a>
    <ul>
	  <li><a href="<?=OS_HOME?>adm/?users&amp;edit=<?=$_SESSION["user_id"]?>">Edit Account</a></li>
	  <li><a href="<?=OS_HOME?>">Go to OS&raquo; </a></li>
	  <li><a href="<?=OS_HOME?>adm/?logout">(logout)</a></li>
	</ul>
  </li>
</ul> 
</div>
</div>

<div align="center" style="background-color: #fff; width: 960px; margin: 0 auto; padding-top: 18px; padding-bottom: 28px; border: 10px solid #2B0202; border-radius: 10px;">
   <?php if ($TotalGamesForUpdate>=1) { ?>
   Unranked Games: <?=$TotalGamesForUpdate?>
   <a class="menuButtons" href="<?=OS_HOME?>adm/update_stats.php?start&amp;refresh=5">Update ALL</a>
   <a class="menuButtons" href="<?=OS_HOME?>adm/update_stats.php?reset">Reset ALL stats</a>
   <?php
   if ( isset($return)  AND !empty($return) ) { ?>
   <div style="margin-top: 16px;">
   <textarea style="width: 400px; height: 290px;"><?=$return?></textarea>
   </div>
   <?php if (isset($_GET["refresh"]) AND is_numeric($_GET["refresh"]) AND isset($_GET["start"]) AND $TotalGamesForUpdate>=1) {  ?>
   <h2>Please wait...updating stats</h2>
   <?php } ?>
   <?php } ?>
   <?php } else { ?>
   <div>Unranked Games: <?=$TotalGamesForUpdate?></div>
   <h2>There is no games for update.</h2>
   <div class="padTop"></div>
   <a class="menuButtons" href="<?=OS_HOME?>adm/update_stats.php?reset">Reset ALL stats</a>
   <?php } ?>
</div>

</div>

<div style="margin-top: 20px;">&nbsp;</div>
<?php
      include('../themes/'.$DefaultStyle.'/footer.php');
 }
?>